package com.spark.common.helper

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.LogUtils
import org.json.JSONObject
import java.lang.StringBuilder

class JpushNotifyReceiver : BroadcastReceiver() {
    companion object {
        val messageReceivedAction = "com.spark.career.MESSAGE_RECEIVED_ACTION"
        val keyTitle = "title"
        val keyMessage = "message"
        val keyExtras = "extras"
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.apply {
            val bundle = extras
            LogUtils.e("【接收到的消息】${print(bundle)}")
            when (action) {
                JPushInterface.ACTION_REGISTRATION_ID -> {
                    val registerId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID)
                    LogUtils.e("【RegisterId】$registerId")
                }
                JPushInterface.ACTION_MESSAGE_RECEIVED -> {
                    val message = bundle.getString(JPushInterface.EXTRA_MESSAGE)
                    LogUtils.e("【CustomMessage】$message")
                    handleCustomMsg(context, bundle)
                }
                JPushInterface.ACTION_NOTIFICATION_RECEIVED -> {
                    val notifyId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID)
                    LogUtils.e("【NotifyId】$notifyId")
                }
                JPushInterface.ACTION_NOTIFICATION_OPENED -> {
                    LogUtils.e("【UserOpenedTheNotify】")
                    // 打开自定义Activity
                }
                JPushInterface.ACTION_RICHPUSH_CALLBACK -> {
                    LogUtils.e("【RichPushCallback】")
                    // 此处根据 JPushInterface.EXTRA_EXTRA的内容处理代码，如打开新 Activity,打开一个网页...
                }
                JPushInterface.ACTION_CONNECTION_CHANGE -> {
                    LogUtils.e("【ConnectionStateChanged】")
                }
                else -> {
                    LogUtils.e("【UnHandledAction】${intent.action}")
                }
            }
        }
    }

    private fun print(bundle: Bundle): String {
        var outStr = StringBuilder()

        bundle.keySet().forEach {
            when (it) {
                JPushInterface.EXTRA_NOTIFICATION_ID -> outStr.append("\n【key】$it【value】${bundle.getInt(it)}")
                JPushInterface.EXTRA_CONNECTION_CHANGE -> outStr.append("\n【key】$it【value】${bundle.getBoolean(it)}")
                JPushInterface.EXTRA_EXTRA -> {
                    val extra = bundle.getString(JPushInterface.EXTRA_EXTRA)
                    if (!extra.isNullOrBlank()) {
                        val jo = JSONObject(extra)
                        jo.keys().forEach {
                            outStr.append("\n【key】$it【value】${jo.optString(it)}")
                        }
                    }
                }
                else -> outStr.append("\n【key】$it【value】${bundle.get(it)}")
            }
        }
        return outStr.toString()
    }

    private fun handleCustomMsg(context: Context?, bundle: Bundle) {
        bundle.apply {
            val msg = getString(JPushInterface.EXTRA_MESSAGE)
            val extraStr = getString(JPushInterface.EXTRA_EXTRA)
            //todo 装载目标对象
            val intent = Intent(messageReceivedAction)
            intent.putExtra(keyMessage, msg)
            if (!extraStr.isNullOrBlank()) {
                val jo = JSONObject(extraStr)
                if (jo.length() > 0) {
                    intent.putExtra(keyExtras, extraStr)
                }
            }
            context?.apply {
                LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent)
            }
        }
    }
}